<template>
  <div class="setting-message-channel-sms">
    
    <!-- 客服电话 start-->
    <div class="setting-item">
      <ui-title 
        :title="$t('setting.messageChannel.customerServicePhone')"
        :tips="$t('setting.messageChannel.tip.smsTip')"
      />
      <div class="scope tel-num">
        <span class="label">{{$t('common.base.phone')}}</span>
        <el-input v-model="telnum" :placeholder="$t('setting.messageChannel.tip.inputPhone')" maxlength="13"></el-input>
        <el-button type="primary" :disabled="pending" @click="saveTel">{{$t('common.base.save')}}</el-button>
      </div>
    </div>
    <!-- 客服电话 end-->
    
    <!-- start 签名设置 旧 -->
    <div class="setting-item" v-if="isOldSmsSign">
      <ui-title :title="$t('setting.messageChannel.signSetting')" />
      <div class="scope scope-container">
        <span class="sms-sign">{{$t('setting.messageChannel.smsSign')}}
          <el-tooltip :content="$t('setting.messageChannel.smsSignConfig[0]')">
            <template slot="content">
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig[1]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig[2]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig[3]') }}
              </p>
            </template>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip> 
        </span>
        <span class="sms-sign-content">
          {{ sign }}
          <i class="iconfont icon-edit-square" @click="updateSign"></i>
        </span>
      </div>
      <!-- start 资质认证 -->
      <div class="qualification-container">
        修改签名，请先进行
        <el-button type="text" @click="openQualificationDialog">
          资质认证
        </el-button>
      </div>
      <!-- end 资质认证 -->
    </div>
    <!-- end 签名设置 旧 -->
    
    <!-- start 签名设置 新 -->
    <div class="setting-item" v-if="isNewSmsSign">
      <ui-title :title="$t('setting.messageChannel.signSetting')" />
      <div class="scope scope-container sms-scope-container">
        <span class="sms-sign">
          {{ $t('setting.messageChannel.smsSign') }}
          <el-tooltip>
            <template slot="content">
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[0]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[1]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[2]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[3]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[4]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[5]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[6]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[7]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[8]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[9]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[10]') }}
              </p>
              <p class="sms-scope-container-tip-text">
                {{ $t('setting.messageChannel.smsSignConfig2[11]') }}
              </p>
            </template>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip> 
        </span>
        <div class="sms-sign-content">
          
          <span>
            {{ sign }}
          </span>
          
          <div class="sms-sign-approval-status">
            
            <!-- start 已通过 -->
            <el-tag 
              type="success"
              v-if="isSmsAutographApprovalSuccess"
            >
              {{ $t('common.base.usualStatus.passed') }}
            </el-tag>
            <!-- end 已通过 -->
            
            <!-- start 审核中 -->
            <el-tag 
              type="warning"
              v-if="isSmsAutographApprovalPending"
            >
              {{ smsAutographApprovalPendingText }}
            </el-tag>
            <!-- end 审核中 -->
            
            <!-- start 审核失败 -->
            <el-tag 
              type="danger"
              v-if="isSmsAutographApprovalFail"
              @click="onSmsAutographApprovalFailClick"
            >
              {{ smsAutographApprovalFailText }}
            </el-tag>
            <!-- end 审核失败 -->
            
          </div>
          
          <i 
            v-if="isShowEditSign"
            class="iconfont icon-edit-square" 
            @click="updateSign"
          >
          </i>
          
        </div>
      </div>
      <!-- start 资质认证 -->
      <div class="qualification-container">
        修改签名，请先进行
        <el-button type="text" @click="openQualificationDialog">
          资质认证
        </el-button>
      </div>
      <!-- end 资质认证 -->
    </div>
    <!-- end 签名设置 新 -->

    <!-- 短信余量 start-->
    <div class="setting-item">
      <ui-title :title="$t('setting.messageChannel.smsBalance')" />

      <UseCard
        ref="useCardRef"
        :title="$t('setting.messageChannel.smsCount')"
        :styleObj="{
          icon:'icon-duanxinxiaoxishezhi',
          iconBgcolor:'#52C41A',
          cardBgColor:'linear-gradient(315deg,#fff,#fcfefb 71%,#f8fff4 100%,#f8fff4 0)'
        }"
        :cardData="cardData"
        :showWelfareBtn="showWelfareBtn"
        @openWelFare="openWelFare"
      >
        <div class="flex">
          <el-button type="primary" @click="pay">{{$t('common.base.recharge')}}</el-button>
          <el-button @click="payRecord">{{$t('setting.messageChannel.rechargeRecord')}}</el-button>
        </div>
      </UseCard>
    </div>
    <!-- 短信余量 end-->

    <!-- 短信模板设置 start-->
    <div class="setting-item setting-tpl-item">
      <ui-title :title="$t('setting.messageChannel.smsTemplateSetting')" />
      <div class="scope tpl-content">
        <el-button type="primary" class="apply-tpl" @click="applyTpl">{{$t('setting.messageChannel.applyTemplate')}}</el-button>
        <sms-template-record @edit="editTpl" ref="smsTemplateRecordRef"></sms-template-record>
      </div>
    </div>
    <!-- 短信模板设置 end-->
    
    <sms-pay ref="smsPayRef"></sms-pay>
    
    <!-- start 更新签名 -->
    <update-sign 
      ref="signRef" 
      @update="update" 
      @openQualificationDialog="openQualificationDialog"
    >
    </update-sign>
    <!-- end 更新签名 -->
    
    <sms-template ref="smsTemplateRef" @updateSmsTemplate="updateTpl"></sms-template>
   
    <el-dialog :title="$t('setting.messageChannel.rechargeRecord')" :visible.sync="smsPayRecordVisible" width="800px">
      <div class="time-search">
        <span>{{$t('setting.messageChannel.byTimeQuery')}}</span>
        <el-date-picker
          v-model="datePicker"
          style="width: 100%;"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="-"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          :clearable="false"
          @change="dateChange"
          :default-time="['00:00:00', '23:59:59']"
          value-format="timestamp"
          :picker-options="pickerOptions">
        </el-date-picker>
      </div>

      <sms-pay-record v-if="smsPayRecordVisible"  :date="datePicker" ref="smsPayRecordRef"></sms-pay-record>
      <div slot="footer" class="dialog-footer">
        <el-button @click="smsPayRecordVisible = false">{{$t('common.base.cancel')}}</el-button>
      </div>
    </el-dialog>
    
    <!-- start 资质弹窗 -->
    <QualificationDialog
      ref="QualificationDialog"
    />
    <!-- end 资质弹窗 -->

  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
/* mixin */
import timeSearchMixin from '@src/mixins/timeSearchMixin/index.js'

import * as SettingApi from '@src/api/SettingApi';
import UseCard from './use-card.vue';
import SmsPay from '@src/modules/doMyself/setting/smsMessage/components/SmsPay.vue';
import SmsPayRecord from '@src/modules/doMyself/setting/smsMessage/components/SmsPayRecord.vue';
import UpdateSign from '@src/modules/doMyself/setting/smsMessage/components/UpdateSign.vue';
import SmsTemplate from '@src/modules/doMyself/setting/smsMessage/components/SmsTemplate.vue';
import SmsTemplateRecord from '@src/modules/doMyself/setting/smsMessage/components/SmsTemplateRecord.vue';
import SmsSendRecord from '@src/modules/doMyself/setting/smsMessage/components/SmsSendRecord.vue';
import { QualificationDialog } from '@src/modules/setting/messageChannel/components/qualification'
/* util */
import qs from '@src/util/querystring';
import { validatePhone } from '@src/util/validator'
import { t } from '@src/locales'
import MsgModel from '@model/MsgModel';
import { getSmsAutograph, getSmsSupplier } from '@src/api/MessageApi'
import { SmsAutographApprovalStatusEnum, SmsSupplierEnum } from '@model/biz/SMS'
import { isFalsy, getRootWindow } from 'pub-bbx-utils';

export default {
  name: 'setting-message-channel-sms',

  mixins: [timeSearchMixin],

  components: {
    UseCard,
    SmsPay,
    SmsPayRecord,
    UpdateSign,
    SmsTemplate,
    SmsTemplateRecord,
    SmsSendRecord,
    QualificationDialog
  },
  data() {
    return {
      detail: {},
      pending: false,
      telnum: '',
      smsPercentage: 0,
      sign: '',
      smsPayRecordVisible: false,
      cardData:{
        usage:0,
        total:0
      },
      commodityCode: 'smsRecharge', // 短信商品码
      autographData: {},
      isNewSmsSign: false,
    }
  },

  props:{
    openPay:{
      type:Boolean,
      default:false
    },
    //是否展示福利按钮
    showWelfareBtn:{
      type:Boolean,
      default:false
    },
  },

  computed:{
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return getRootWindowInitData().tenantType
    },
    // 短信签名审批状态
    approvalStatus() {
      return this.autographData?.approvalStatus
    },
    // 是否是短信签名待审批状态
    isSmsAutographApprovalPending() {
      return this.approvalStatus == SmsAutographApprovalStatusEnum.PENDING
    },
    // 是否是短信签名审批失败状态
    isSmsAutographApprovalFail() {
      return this.approvalStatus == SmsAutographApprovalStatusEnum.FAILED
    },
    // 是否是短信签名审批成功状态
    isSmsAutographApprovalSuccess() {
      return this.approvalStatus == SmsAutographApprovalStatusEnum.PASSED
    },
    // 是否展示短信签名审批状态标签
    isShowSmsApproveStatusTag() {
      return this.isSmsAutographApprovalFail || this.isSmsAutographApprovalPending
    },
    /**
     * @description 是否展示编辑签名按钮
     * 1. 非短信签名待审批状态
     */
    isShowEditSign() {
      return isFalsy(this.isSmsAutographApprovalPending)
    },
    // 短信签名审批中提示文案
    smsAutographApprovalPendingText() {
      const newAutograph = this.autographData?.newAutograph || ''
      const inReview = this.$t('common.base.inReview')
      return `“${newAutograph}”${inReview}`
    },
    // 短信签名审批失败提示文案
    smsAutographApprovalFailText() {
      const approvalMessage = this.autographData?.approvalMessage || ''
      const auditFailure = this.$t('common.base.auditFailure')
      return `“${approvalMessage}” ${auditFailure}`
    },
    isOldSmsSign() {
      return isFalsy(this.isNewSmsSign)
    }
  },
  watch:{
    openPay(newValue) {
      newValue && this.pay()
    }
  },
  async created () {
    this.getSmsSupplier().then(() => {
      this.initialize();
    })
  },
  mounted() {
    const query = qs.parse(window.location.search);
    if (query?.source === 'active') {
      const scrollHeight = this.$refs.mainRef.scrollHeight;
      this.$nextTick(() => {
        this.$refs.mainRef.scrollTop = scrollHeight;
      })
    }
  },
  methods: {
    getSmsSupplier() {
      this.pending = true
      return (
        getSmsSupplier()
        .then(res => {
          this.isNewSmsSign = res?.data === SmsSupplierEnum.VOLCENGINE
        })
        .catch(err => {
          this.isNewSmsSign = false
          console.error('getSmsSupplier error', err)
        })
        .finally(() => {
          this.pending = false
        })
      )
    },
    initialize(){
      this.getSmsMessageInfo();
      this.getSign();
    },
    addTotal(){
      this.$refs.useCardRef?.addTotal()
    },

    async getSign() {
      
      if (this.isNewSmsSign) {
        this.getSignNew()
        return
      } 
      
      this.getSignOld()
    },
    getSignOld() {
      this.$http.get('/vipsms/getAutograph').then(res => {
        this.sign = res.data;
      })
    },  
    async getSignNew() {
      // 获取短信签名
      const result = await getSmsAutograph()
      
      // 如果失败则提示
      const isFail = MsgModel.isFail(result)
      if (isFail) {
        this.$platform.notification({
          title: t('common.base.fail'),
          message: result.message || t('common.base.fail'),
          type: 'error'
        })
        return
      }

      const data = MsgModel.getData(result, {})
      const autograph = data?.autograph || ''
      const newAutograph = data?.newAutograph || ''
      const approvalStatus = data?.approvalStatus
      const approvalMessage = data?.approvalMessage || ''
      
      this.sign = autograph;
      this.autographData = data;
    },
    updateSign(){
      this.$refs.signRef.openDialog(this.sign);
    },
    update(sign) {

      if (this.isNewSmsSign) {
        this.updateSignNew()
        return
      } 

      this.updateSignOld(sign)
      
    },      
    updateSignOld(sign) {
      this.sign = sign;
    },
    updateSignNew() {
      this.getSignNew();
    },
    async pay(){
      try{
        this.loading = true
        const { status, data = {} } = await SettingApi.getCommodityPackage({commodityCode:this.commodityCode});

        if(status !== 0) return

        const { specs = {}, pack = {} } = data || {}
        this.packCode = pack.code

        let list = []
        specs?.map(item => {
          const { code, discountDesc, name, sellingPrice, unitPrice, unitPriceDivisible } = item;
          const desc = discountDesc.split('_')
          const count = name.split('_')?.[0]

          list.push({
            id:code,
            desc:desc?.[0],
            count,
            price: `￥${sellingPrice?.toFixed(2)}`,
            unit:pack?.priceUnit,
            priceClassName:'price',
            currentPrice: `${unitPriceDivisible ? '= ' : '≈ '}${unitPrice}${t('common.base.yuan')}/${pack?.priceUnit}`
          })
        })
        this.$refs.smsPayRef.openDialog({commodityCode: this.commodityCode,  packCode: this.packCode}, list);
        this.loading = false

      }catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    payRecord(){
      this.smsPayRecordVisible = true;
    },
    // 获取配置信息
    getSmsMessageInfo(){
      SettingApi.getSmsMessageInfo().then(({ status, data, message })=>{
        if(status) return this.$platform.notification({
          title: t('common.base.fail'),
          message: message || '',
          type: 'error'
        })
        this.detail = data || {};
        this.telnum = data.telnum || '';

        const smsCount = this.detail?.smsCount || 0
        const smsUsedCount = this.detail?.smsUsedCount || 0
        this.cardData.usage = smsUsedCount
        this.cardData.total = (+smsCount) + (+smsUsedCount) || 0
      });
    },
    // 新建短信模板
    applyTpl(){
      this.$refs.smsTemplateRef.openDialog();
    },
    // 编辑短信模板
    editTpl(item){
      this.$refs.smsTemplateRef.openDialog(item);
    },
    // 新建和编辑短信模板成功后刷新列表
    updateTpl(){
      this.$refs.smsTemplateRecordRef.search();
    },
    // 保存客服电话
    async saveTel(){
      // 校验400开头
      const reg = /^400[0-9]{7}/;
      if(!validatePhone(this.telnum)) {
        return this.$platform.notification({
          title: t('common.base.saveFail'),
          message: t('setting.messageChannel.tip.inputPhone2'),
          type: 'error'
        });
      }
      if(!this.telnum) return this.$platform.notification({
        title: t('common.base.saveFail'),
        message: t('setting.messageChannel.tip.inputPhone3'),
        type: 'error'
      });
      try {
        this.pending = true;
        const { status, message } = await SettingApi.saveTel({telnum: this.telnum});
        this.pending = false;
        if(status) {
          this.$platform.notification({
            title: t('common.base.saveFail'),
            message: message || '',
            type: 'error'
          })
          return
        } 
        this.$platform.notification({
          title: t('common.base.saveSuccess'),
          type: 'success'
        })
      } catch (error) {
        this.pending = false;
        console.log(error);
      }
    },

    dateChange(event) {
      let data = event?.length === 2 ? event : []
      this.datePicker = data;
      this.$refs.smsPayRecordRef.search(1);
    },

    openWelFare(){
      this.$emit("openWelFare")
    },
    onSmsAutographApprovalFailClick() {
      
      const approvalMessage = this.autographData?.approvalMessage || ''
      const auditFailure = this.$t('common.base.auditFailure')
      
      this.$alert(approvalMessage, auditFailure, {
        confirmButtonText: this.$t('common.base.confirm')
      })

    },
    openQualificationDialog() {
      this.$refs.QualificationDialog.openStatusDialog()
    }
  },
}
</script>

<style lang="scss">
.setting-message-channel-sms {
  .setting-item {
    padding-bottom:12px;
    border-bottom: 1px dashed #E8E8E8;
    &:last-child{
      border:0;
    }
    .scope {
      .sms-sign {
        height: 22px;
        font-size: 14px;
        color: $text-color-primary;
        line-height: 22px;
      }
      .sms-sign-content{
        height: 24px;
        font-size: 14px;
        font-weight: 600;
        color: $text-color-primary;
        line-height: 24px;
        margin-left: 20px;
        i {
          color: $color-primary;
          margin-left: 6px;
          cursor: pointer;
        }
      }
    }
    .scope-container {
      padding: 12px 0 0 12px;
    }
    .sms-amount-container{
      width: 389px;
      background: #FFFFFF;
      box-shadow: 0px 1px 4px 0px rgba(0,0,0,0.1200);
      border-radius: 4px;
      padding: 16px;
      margin:24px 0 0 10px;

      background: linear-gradient(315deg, #FFFFFF 0%, #FCFEFB 71%, #F8FFF4 100%, #F8FFF4 100%);

      .progress{
        margin:16px 0 8px;
      }
      .content-top{
        height: 24px;
        font-size: 16px;
        font-weight: 500;
        color: #262626;
        line-height: 24px;
      }
      .content-bottom{
        height: 22px;
        font-size: 14px;
        font-weight: 400;
        color: #8C8C8C;
        line-height: 22px;
        margin-bottom:20px;
      }
    }
    .tpl-content{
      padding: 16px 0 0 12px;
      .apply-tpl {
        margin-bottom: 24px;
      }
    }
  } 
  .setting-tpl-item {
    border-bottom: none;
  }
  .tel-num {
    display: flex;
    align-items: center;
    margin:12px 0 0 10px;
    .label{
      height: 22px;
      font-size: 14px;
      font-weight: 400;
      color: #262626;
      line-height: 22px;
      margin-right:8px;
      display: inline-block;
    }
    .el-input {
      width: 240px;
    }
    button {
      height: 32px;
      margin-left: 12px;
    }
  }
  
  .el-dialog__headerbtn{
    top: 0;
  }
  .flex-space-between {
    justify-content: space-between;
  }
  .mb-8 {
    margin-bottom: 8px;
  }

}
.time-search {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom:16px;
  .el-date-editor {
    width: 240px!important;
    margin-left: 12px;
  }
}

.sms-scope-container {
  display: flex;
  .sms-sign-content {
    display: flex;
    .el-tag {
      cursor: pointer;
      margin-left: 12px;
      border-radius: 12px;
    }
  }
}

.sms-scope-container-tip-text {
  font-size: 13px;
  margin-top: 6px;
  margin-bottom: 0;
}

.qualification-container {
  padding-left: 12px;
}

</style>